import n from "./AudioManager"
import l from "./PlayerDataSys"
import s from "./SystemDataSys"
import c from "./PeripheralSystemDataMgr"
import u from "./AdvertEventType"
import p from "./EventMgr"
import d from "./Handler"
import h from "./NativeEventType"
import f from "./frameworkManager"
import g from "./GameErrorCatch"
// import y from "./HotUpdate"
import m from "./AdManager"
import _ from "./ClientData"
import v from "./SdkHelper"
import b from "./BaseSystem"
import C from "./EngineUtil"
import T from "./PeripheralSystemMgr"
import M from "./PageMgr"
import NativeUtils from "./NativeUtils"
import HttpHelper from "./HttpHelper"
import ObstacleAniCtrl from "./ObstacleAniCtrl"
import MatchGameData from "./MatchGameData"
import AdManager from "./AdManager"
import PlayerDataSys from "./PlayerDataSys"

const { ccclass, property } = cc._decorator;
@ccclass
export default class Loading extends cc.Component {
    @property(cc.Node)
    progress = null;
    @property(cc.Label)
    pro_title = null;
    @property(cc.Node)
    wxLogin = null;
    @property(cc.Node)
    loading: cc.Node = null;
    @property()
    wx_code = "";
    couldTouch = true;
    hasAgree = false;
    @property(cc.Node)
    agreeImg = null;
    load_count = 0;
    @property(cc.Node)
    check_root = null;
    @property(cc.Label)
    label_progress = null;
    loangAni = [];
    @property(cc.Node)
    agelogoNode = null;
    @property(cc.Node)
    addictionTips = null;
    get_middle_cfg_timer = null;
    get_oaid_timer = null;
    _sdk_init_count = 0;
    isJumpMainScene = false;

    onLoad() {
        this.loangAni.forEach((e) => {
            e.setAnimation(0, "appear", false);
            e.setAnimation(1, "idle", true);
        });
        M.init();
        this.addEvent();
        this.hotUpdate();
        //请求广告配置
        AdManager.getAdConfig();
        // C.getLocalData("user_agreement") ? v.initOtherSDK(true) : M.showPage("AgreementPage");
    };

    start() {
        this.agelogoNode.active = false;
        NativeUtils.gameLoadSuccess();

    };

    onDestroy() {
        this.removeEvent();
    };

    addEvent() {
        p.listen(h.GET_WECHAT_CODE, this.onGetWxCode, this);
        p.listen(h.AUTHOR_FINISH, this.onAuthorFinish, this);
        p.listen(h.OAID_FINISH, this.oaidFinish, this);
        p.listen(u.ON_SPLASH_FINISH, this.jumpScene, this);
    };

    removeEvent() {
        p.ignore(h.GET_WECHAT_CODE, this.onGetWxCode, this);
        p.ignore(h.AUTHOR_FINISH, this.onAuthorFinish, this);
        p.ignore(h.OAID_FINISH, this.oaidFinish, this);
        p.ignore(u.ON_SPLASH_FINISH, this.jumpScene, this);
    };

    onAuthorFinish() {
        f.log("----onAuthorFinish");
        p.ignore(h.AUTHOR_FINISH, this.onAuthorFinish, this);
        this.checkSdk();
    };

    oaidFinish() {
        f.log("----oaidFinish");
        p.ignore(h.OAID_FINISH, this.oaidFinish, this);
        this.checkSdk();
    };

    checkSdk() {
        f.log("checkSdk====", this._sdk_init_count);
        this._sdk_init_count++;
        if (this._sdk_init_count >= 2) {
            this.hotUpdate();
        }
    };

    hotUpdate() {
        // var e = this;
        // f.log("开始热更新");
        // s.init();
        // if ("huawei" !== _.channel_name) {
        //     this.agelogoNode.active = true;
        // }
        // var t = s.get_version_url(),
        //     a = _.getVersionData();
        // s.update_user_url("device_id", _.device_id);
        // s.update_privacy_url("device_id", _.device_id);
        // y.getInstance().checkGrayUpdate(t + "?" + a, function (t) {
        //     if (t) {
        //         f.log("grayUpdate canUpdate");
        //         y.getInstance().hotUpdate(function (t, a) {
        //             if (t < 0) {
        //                 f.log("热更新 完成");
        //                 e.setProgress(.5);
        //                 e.init();
        //             }
        //             if (a && a.code == jsb.EventAssetsManager.UPDATE_PROGRESSION) {
        //                 f.log(a.file_percent, "进度");
        //                 e.setProgress(.5 * a.file_percent);
        //             }
        //         });
        //     } else {
        //         e.init();
        //     }
        // });
        this.init();
    };

    init() {
        f.log("loading init");
        n.getInstance().init();
        this.getMiddleCfg();
        c.addLocalMapPointJson();
        g.init();
        this.getSystemConfig();
    };

    checkReport() {
        // var e = cc.sys.localStorage.getItem("user_LastAgreement");
        // if (e) {
        //     b.agreementReport({
        //         url: e,
        //         type: "user"
        //     });
        //     cc.sys.localStorage.removeItem("user_LastAgreement");
        //     v.reportData("U_WATCH_RULE", {
        //         rule_type: "agreement"
        //     });
        // }
        // var t = cc.sys.localStorage.getItem("user_LastPrivacy");
        // if (t) {
        //     b.agreementReport({
        //         url: t,
        //         type: "privacy"
        //     });
        //     cc.sys.localStorage.removeItem("user_LastPrivacy");
        //     v.reportData("U_WATCH_RULE", {
        //         rule_type: "privacy"
        //     });
        // }
    };

    getMiddleCfg() {

        // "{\"location_flag\":false,\"vv_flag\":false,\"forbid_screen\":false,\"forbid_red_envelope\":false,\"sm_flag\":true,\"td_flag\":true,\"hs_flag\":true,\"notice_content\":\"\",\"per_dialog_delay\":7200,\"notice_delay\":10,\"ck_flag\":false,\"tly_flag\":false,\"force_flag\":false,\"tab_flag\":false,\"ysdk_flag\":true,\"dir_flag\":true,\"antian_flag\":false,\"req_perm_flag\":false,\"new_add_flag\":true,\"pay_flag\":false,\"hw_flag\":false,\"tt_flag\":false}"]


        // var e = this;
        // f.log("开始获取中台配置");
        // var t = v.getMiddleConfig();
        // f.log("中台配置1111====", t);
        // if (t) {
        //     this.onGetMiddleCfg(t);
        // } else {
        //     p.listen(h.ON_GET_MIDDLE_CONFIG, this.onGetMiddleCfg, this);
        //     var a = cc.sys.isNative ? 1e4 : 1e3;
        //     this.get_middle_cfg_timer && clearTimeout(this.get_middle_cfg_timer);
        //     f.log("中台配置计时====", t);
        //     this.get_middle_cfg_timer = setTimeout( () =>{
        //         e.onGetMiddleCfg();
        //     }, a);
        // }
    };

    onGetMiddleCfg(e) {
        // void 0 === e && (e = "{}");
        // this.get_middle_cfg_timer && clearTimeout(this.get_middle_cfg_timer);
        // p.ignore(h.ON_GET_MIDDLE_CONFIG, this.onGetMiddleCfg, this);
        // f.log("获取中台配置2222====", e);
        // s.init_middle_config(e);
        // this.getSystemConfig();
        // this.dealShowDddictionTip();
    };

    dealShowDddictionTip() {
        // var e = _.channel_name,
        //     t = s.auth_type;
        // if ("baidu" == e && t) {
        // this.addictionTips.active = true;
        // this.wxLogin.y = -260;
        // } else {
        // this.addictionTips.active = false;
        // this.wxLogin.y = -399;
        // }
    };

    loadGuidePage() {
        this.progressFinish();
    };

    reportConfigCount() {
        var e = C.getLocalData("key_request_config");
        e || (e = "1");
        v.reportData("u_request_config", {
            get_count: e
        });
        var t = Number(e);
        t++;
        C.setLocalData("key_request_config", String(t));
    };

    getSystemConfig(e?) {
        var t = this;
        f.log("getSystemConfig 系统配置");
        // b.getSystemConfig(d.create(this, function (a) {
        let a = { "code": 1, "message": "", "data": { "is_encrypt": true, "new_user": 0, "position": "Turkey", "tourists_submit": false } };
        f.log("服务器 返回系统配置", a);
        e && f.reconnectSuc();
        s.init_config(a.data);

        t.agelogoNode.active = true;
        v.requestSMId();
        t.autoLogin();
        // ), d.create(this, function (a) {
        //     e && f.reconnectFai();
        //     f.httpErr(a,  (e) => {
        //         t.getSystemConfig(e);
        //     });
        // }));
    };

    autoLogin(e?) {
        // var t = this;
        // f.log("自动登录");
        // var a = v.requestTDId(),
        //     o = a ? {
        //         black_box: a
        //     } : null;
        // b.autoLogin(o, d.create(this, function (a) {
        //     f.log("autoLogin res: ", a);
        //     var o = "";
        //     a.data && (o = a.data.yid);
        //     e && f.reconnectSuc();
        //     f.log("yid不存在走====微信登录", o);
        //     if (o) {
        //         l.initUserId(a.data);
        //         t.getGameConfig();
        //     } else if (cc.sys.isNative) {
        //         t.wxLogin.active = true;
        //         t.loading.active = false;
        //     } else {
        //         t.touristsLogin();
        //     }
        // }), d.create(this, function (a) {
        //     e && f.reconnectFai();
        //     f.httpErr(a,  (e) => {
        //         t.autoLogin(e);
        //     });
        // }));
        this.touristsLogin();
    };

    touristsLogin() {


        var t = this;
        // f.log("touristsLogin: ");
        // var a = v.requestTDId(),
        //     o = a ? {
        //         black_box: a
        //     } : null;
        // b.touristsLogin(o, d.create(this, function (a) {
        //     f.log("touristsLogin res: ", a);
        //     e && f.reconnectSuc();
        //     if (-8888 != a.code) {
        l.initUserId({ "yid": "195361553811_7706088328" });
        t.getGameConfig();
        //     } else {
        //         t.wxLogin.active = true;
        //         t.loading.active = false;
        //     }
        // }), d.create(this, function (a) {
        //     e && f.reconnectFai();
        //     f.httpErr(a,  (e) => {
        //         t.touristsLogin(e);
        //     });
        // }));
    };

    getGameConfig() {
        console.log("getGameConfig: ");
        this.getUserInfo();
    };

    reportData(gamelevel) {
        // 检查本地存储中是否存在时间值
        const storedTime = localStorage.getItem('lastLoginTime');
        let isFirstLogin, lastOutTime = "";
        let loginDays = 0;
        let consecutiveLoginDays = 0;


        // 更新累计登录天数
        const currentDate = new Date().toLocaleDateString();
        const storedDate = localStorage.getItem('lastLoginDate');
        if (storedDate === currentDate) {
            // 当前日期与上次登录日期相同，不增加累计登录天数
            loginDays = parseInt(localStorage.getItem('loginDays'));
            consecutiveLoginDays = parseInt(localStorage.getItem('consecutiveLoginDays'));
        } else {
            // 当前日期与上次登录日期不同，增加累计登录天数
            loginDays = parseInt(localStorage.getItem('loginDays')) + 1;
              // 上次登录是昨天，连续登录天数加1
            consecutiveLoginDays = parseInt(localStorage.getItem('consecutiveLoginDays')) + 1;
            localStorage.setItem('lastLoginDate', currentDate);
            localStorage.setItem('loginDays', loginDays + "");
            localStorage.setItem('consecutiveLoginDays', consecutiveLoginDays + "");
        }

        NativeUtils.userSet({ 'last_login_time': lastOutTime });
        NativeUtils.userSet({ 'total_login_day': loginDays || 1});
        NativeUtils.userSet({ 'continuous_login_day': consecutiveLoginDays || 1});


        if (storedTime) {
            // 存在时间值，表示不是新用户
            isFirstLogin = false;
            lastOutTime = storedTime;
        } else {
            // 不存在时间值，表示是新用户
            isFirstLogin = true;
            NativeUtils.userSet({ 'first_login_time':  this.formatCurrentTime('yyyy-MM-dd HH:mm:ss') });
        }
        NativeUtils.userSet({ 'last_login_time': lastOutTime });

        // 定时存储当前时间，并更新上次登出时间
        setInterval(() => {
            const currentTime = this.formatCurrentTime('yyyy-MM-dd HH:mm:ss');

            // 存储当前时间
            localStorage.setItem('lastLoginTime', currentTime);

            // 更新上次登出时间
            lastOutTime = currentTime;

        }, 1000);

        // 上报用户数据的函数
        function reportUserData(isFirstLogin, lastOutTime) {
            const userData = {
                level_id: gamelevel,
                is_first_login: isFirstLogin,
                last_out_time: ""
            };

            if (lastOutTime) {
                userData.last_out_time = lastOutTime;
            }
            // 执行上报逻辑，将userData对象发送到服务器
            NativeUtils.report2('role_login', userData);
        }

        // 上报字段名为 last_out_time
        reportUserData(isFirstLogin, lastOutTime);
    }

    formatCurrentTime(dateFormat) {
        const currentDate = new Date();

        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getDate()).padStart(2, '0');
        const hours = String(currentDate.getHours()).padStart(2, '0');
        const minutes = String(currentDate.getMinutes()).padStart(2, '0');
        const seconds = String(currentDate.getSeconds()).padStart(2, '0');
        const milliseconds = String(currentDate.getMilliseconds()).padStart(3, '0');

        let formattedDate = dateFormat.replace('yyyy', year);
        formattedDate = formattedDate.replace('MM', month);
        formattedDate = formattedDate.replace('dd', day);
        formattedDate = formattedDate.replace('HH', hours);
        formattedDate = formattedDate.replace('mm', minutes);
        formattedDate = formattedDate.replace('ss', seconds);

        if (dateFormat.includes('SSS')) {
            formattedDate = formattedDate.replace('SSS', milliseconds);
        }

        return formattedDate;
    }

    async getUserInfo() {
        var t = this;
        console.log("获取玩家信息");
        NativeUtils.cocosInit(e => {
            console.log("cocosInit", JSON.stringify(e));
        })

        await new Promise((resolve) => {
            HttpHelper.getInstance().wxRequestGet('/dispel/userMessage', (d) => {
                console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',d)
                let result = d;
                this.reportData(result.gameLevel);
                console.log("返回用户信息", JSON.stringify(d));
                MatchGameData.gameLevel = result.gameLevel;
                MatchGameData.setPropInfo(result.props);
                PlayerDataSys.updateGoldBalace(result.gold);
                resolve(true);
            }, (d) => {
                resolve(true);
                console.log(1111111333, JSON.stringify(d));
            })
        })

        // b.getUserInfo(d.create(this, function (a) {
        //     f.log("res: ", a);
        //     if (a && -777 == a.code) f.log("黑名单禁止玩家进入"); else {
        //         e && f.reconnectSuc();
        //         if (a && a.code > 0) {

        const data = { "user_info": { "create_time": "2023-09-12 12:27:10", "gender": "保密", "headimgurl": null, "is_tourists": true, "nickname": null, "login_days": 1, "gold_balance": 0, "cash_balance": 0, "reco_switch": 1, "is_reviewer": 0, "not_tf": 1, "fake_balance": 0 }, "game_info": { "traval_data": { "location": 1, "current": 1, "total": 5, "need": 4, "need_total": 5, "now": 1, "xizang": 474, "split_list": [{ "end": 554, "per": 0.003 }, { "end": 624, "per": 0.002 }, { "end": 844, "per": 0.001 }, { "end": 4844, "per": 0.0001 }] }, "yes_clock_data": {}, "clock_data": { "task_id": "1", "reward_type": 1, "reward": 300, "need": 7, "total": 7, "current": 0, "get_status": 0 }, "clock_days": 0, "sroll_msg_list": [{ "type": 1, "name": "红红火火", "image": "https://thirdwx.qlogo.cn/mmopen/vi_32/icZsCPuSZpcZ0e5pNcdj8FW00KHib2ZyVc6I8L4oe0IczqxqHvkc4ib4SKiavnfpHYaucuEA5go0MS0jxBsldUqEKg/132", "extract": 12143 }], "step": 11, "level_step": 0, "event_type": 0, "travel_reward_info": { "gold": 0, "cash": 800 }, "game_level": 2, "extract_count": 0, "map_version": "20230605-01" }, "ab_info": { "ab_gqtc_flag": "s1", "ab_gncd": "s1", "ab_cpsy_flag": "s2", "ab_lxjjyh_flag": "s1", "ab_lcsmzq_flag": "s1", "ab_btlj_flag": "s0", "ab_jssy": "s0", "ab_ltkbt_flag": "s0", "ab_dmth_flag": "s0", "ab_lt2_flag": "s0", "ab_btlj2_flag": "s0", "ab_dmth2_flag": "s0", "ab_qtlj_flag": "s0" } };

        l.init(data);
        // f.log("展示开屏状态=========reviewing_splash", s.reviewing_splash);
        // f.log("展示开屏状态=========is_new_user", s.is_new_user());
        // if (!s.reviewing_splash && !s.is_new_user()) {
        //     m.getInstance().loadNewSplashAd();
        //     c.reportVideoBuriedPoint(VideoBuriedPoint.SPLASH_AD);
        //     return;
        // }
        await this.loadResources();
        setTimeout(() => {
            t.jumpScene();
        }, 1000);

        //         } else v.showToast("登录失败");
        //     }
        // }), d.create(this, function (a) {
        //     e && f.reconnectFai();
        //     f.httpErr(a,  (e) => {
        //         t.getUserInfo(e);
        //     });
        // }));
    };

    private totalResourceCount = 3; // 资源总数量
    private loadedResourceCount = 0; // 已加载资源数量
    private targetProgress = 0; // 目标进度

    async loadResources() {
        var d = ObstacleAniCtrl.init();

        await this.loadResourceAsync(`prefabs/TopUi`, cc.Prefab);
        await this.loadResourceAsync(`prefabs/PandaTravel`, cc.Prefab);
        await this.loadResourceAsync(`prefabs/MatchGameView`, cc.Prefab);

        var results = await Promise.all([d]);
        var topUiPrefab = results[0];

        // 在这里可以执行相应的操作，比如实例化 prefab 或进行其他逻辑处理
        // 示例代码中只是将结果保存在变量中，您可以根据实际需求进行相应的处理

        console.log("资源加载完成");
    }

    private async loadResourceAsync<T extends cc.Asset>(path: string, type: typeof cc.Asset) {
        return new Promise((resolve, reject) => {
            cc.resources.load(path, type,
                (finish, total, item) => {
                    this.onProgress(finish, total, item); // 进度回调
                },
                (error, asset) => {
                    if (error) {
                        reject(error);
                    } else {
                        this.loadedResourceCount++; // 加载的资源数量加一
                        this.targetProgress = this.loadedResourceCount / this.totalResourceCount; // 计算目标进度
                        this.updateProgress(this.targetProgress); // 更新进度条
                        resolve(asset as T);
                    }
                }
            );
        });
    }

    private onProgress(finish: number, total: number, item) {
        // 在这里可以进行进度处理，比如更新进度条显示
        let progress = finish / total;
        this.updateProgress(progress);
    }

    private updateProgress(progress: number) {
        let increment = 0.01; // 每帧增加的进度值
        let progressBar = this.loading.getComponent(cc.ProgressBar);

        // 通过逐帧动画逐渐增加进度
        let update = () => {
            if (progressBar.progress < progress) {
                progressBar.progress += increment;
                setTimeout(() => {
                    update();
                }, 16);
            }
        };
        update();
    }

    jumpScene() {
        f.log("跳转了======jumpScene");
        if (!this.isJumpMainScene) {
            this.isJumpMainScene = true;
            this.checkReport();
            this.progressFinish();
        }
    };

    touch_wxLogin() {
        this.touristsLogin();
        return;

        var e = this;
        f.log("点击微信登录");
        if (this.hasAgree) {
            if (this.couldTouch) {
                v.reportData("start_registration", null, true);
                this.couldTouch = false;
                this.unscheduleAllCallbacks();
                this.scheduleOnce(function () {
                    e.couldTouch = true;
                }, 3);
                f.log("开始调用微信");
                v.callWxLogin();
            }
        } else v.showToast("请先同意用户协议及隐私政策");
    };

    onGetWxCode(e) {
        return;
        this.wx_code = e;
        f.log("获取到wxcode", e);
        this.getWxInfo();
    };

    getWxInfo(e) {
        return;
        var t = this;
        f.log("getWxInfo: ");
        var a = v.requestTDId(),
            o = a ? {
                black_box: a
            } : null;
        b.wechatLogin({
            wechat_code: this.wx_code,
            tempData: o
        }, d.create(this, function (a) {
            e && f.reconnectSuc();
            var o = a.code;
            if (o < 0) v.showToast(a.message); else {
                t.wxLogin.active = false;
                t.loading.active = true;
                f.log("微信登录成功");
                f.log(a);
                l.initWxData(a.data);
                v.reportData("complete_registration", {
                    code: o
                }, true);
                v.reportData("complete_registration", {
                    code: o
                });
                v.showToast("登录成功");
                t.getGameConfig();
            }
        }), d.create(this, function (a) {
            e && f.reconnectFai();
            f.httpErr(a, (e) => {
                t.getWxInfo(e);
            });
        }));
    };

    touch_agree() {
        this.hasAgree = !this.hasAgree;
        this.agreeImg.active = this.hasAgree;
    };

    progressFinish() {
        var e = this;
        this.load_count++;
        if (this.load_count >= 1) {
            cc.director.preloadScene("main", function (t, a) {
                e.setProgress(t / a * .5 + .5);
            }, function () {
                cc.director.loadScene("main");
            });
        }
    };

    setProgress(e) {
        var t = Math.ceil(100 * e);
        cc.isValid(this.label_progress) && (this.label_progress.string = t + "%");
        isNaN(t) && (t = 1);
        var a = C.getProgressWidth(e, 20, 560).width;
        a < this.progress.width || cc.isValid(this.progress) && (this.progress.width = a);
    };
}